package models

import (
	"strconv"

	"github.com/astaxie/beego/orm"
)

type AiFlowContent struct {
	Id           int64
	Ai_speak     string
	People_speak string
	Call_id      string
	Voice_path   string
	Flow_time    string
	Node_name    string
	Description  string
	Match_key    string
	Process_id    int64
}

func (a *AiFlowContent) TableName() string {
	return TableName("flow_content")
}

func AiFlowContentGetList(page, pageSize int, filters ...interface{}) ([]*AiFlowContent, int64) {
	offset := (page - 1) * pageSize
	list := make([]*AiFlowContent, 0)
	query := orm.NewOrm().QueryTable(TableName("flow_content"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)

	return list, total
}

func AiFlowContentToProcessDesc(id int64) (string) {
	processDesc := ""
	SqlStr := "SELECT node_desc FROM ai_process WHERE id=" + strconv.FormatInt(id, 10)
	err1 := orm.NewOrm().Raw(SqlStr).QueryRow(&processDesc)
	if err1 != nil {
		ErrorLog(err1)
	}

	return processDesc
}

func AiFlowContentGetListAll(filters ...interface{}) ([]*AiFlowContent, int64) {
	list := make([]*AiFlowContent, 0)
	query := orm.NewOrm().QueryTable(TableName("flow_content"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("flow_time").All(&list)

	return list, total
}
func IsRuntimeByCallId(callid string, userId int) (bool, error) {
	//var authStr = " "
	//if userId != 1 {
	//	authStr = " and cdr.account_id=" + strconv.Itoa(userId)
	//}

	sqlStr := "SELECT count(1) FROM ai_runtime WHERE call_id='" + callid + "'"
	var flowCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&flowCount)
	if err != nil {
		ErrorLog(err)
		return false, err
	}
	if flowCount != 0 {
		return true, nil
	}
	return false, nil
}

func (a *AiFlowContent) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}

//获取列表
func GetFlowCount(userId int) (int, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and cdr.account_id=" + strconv.Itoa(userId)
	}

	sqlStr := "SELECT count(1) " +
		" FROM ai_cdr cdr " +
		" where TO_CHAR(cdr.start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd')" +
		" and duration>0" + authStr

	var flowCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&flowCount)
	if err != nil {
		ErrorLog(err)
		return 0, err
	}

	return flowCount, nil
}

//获取列表
func SearchCdr(taskId int64, start, end, caller, timemax, timemin,classify,uuid string, intention, page, pageSize int, userId int) ([]AiCdr, int64, error) {
	//var authStr = " "
	//if userId != 1 {
	//	authStr = " and account_id=" + strconv.Itoa(userId)
	//}

	taskStr := " "
	callerStr := " "
	intentionStr := " "
	limit := " "
	timemaxStr := " "
	timemimStr := " "
	useridStr := " "
	classifyStr := " "
	uuidStr := " "

	if caller != "" {
		callerStr = " AND caller='" + caller + "'"
	}

	if timemax != "" {
		timemaxStr = " AND duration>=" + timemax
	}

	if timemin != "" {
		timemimStr = " AND duration<=" + timemin
	}

	if taskId != 0 {
		taskStr = " AND task_id=" + strconv.FormatInt(taskId, 10)
	}

	if intention != 0 {
		intentionStr = " AND intention=" + strconv.Itoa(intention-1)
	}

	if uuid != "" {
		uuidStr = " AND call_id='" + uuid + "'"
	}

	if classify != "-1" {
		a,_:=strconv.Atoi(classify)
		if a >= 3 {
			classifyStr = " AND talk_crycle>=" + classify
		}else {
			classifyStr = " AND talk_crycle=" + classify
		}
	}

	if userId != 1 {
		useridStr = " AND account_id=" + strconv.Itoa(userId)
	}

	if page == 0 && pageSize == 0 {
	} else {
		limit = " ORDER BY start_time DESC LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
	}

	sqlStr := "SELECT Id,Account_id,Callee,Caller,Start_time,End_time,Route_id,Fee_rate,Duration,Bill_balance,Record_base,Record_path,Task_id,Call_id,Intention,Hangup_dispostion,Term_cause,Term_status,Talk_crycle FROM ai_cdr WHERE" +
		" start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS')  AND" +
		" start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS')" +
		taskStr +
		callerStr +
		intentionStr +
		timemaxStr +
		timemimStr +
		classifyStr+
		uuidStr +
		useridStr +
		limit

	var flowCount []AiCdr
	_, err := orm.NewOrm().Raw(sqlStr).QueryRows(&flowCount)
	if err != nil {
		ErrorLog(err)
		return []AiCdr{}, 0, err
	}
	sqlcountStr := "SELECT count(1) FROM ai_cdr WHERE" +
		" start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS')  AND" +
		" start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS')" +
		taskStr +
		callerStr +
		timemaxStr +
		timemimStr +
		intentionStr +
		classifyStr+
		useridStr
	var count int64
	err = orm.NewOrm().Raw(sqlcountStr).QueryRow(&count)
	if err != nil {
		ErrorLog(err)
		return []AiCdr{}, 0, err
	}

	return flowCount, count, nil
}

//获取子列表
func SearchCdr1(start string, userid int, page, pageSize int) ([]AiCdr, int64, error) {
	//var authStr = " "
	//if userId != 1 {
	//	authStr = " and account_id=" + strconv.Itoa(userId)
	//}
	intentionStr := " "
	if userid != 1 {
		intentionStr = " where account_id=" + strconv.Itoa(userid)
	}
	var limit = " "
	if page == 0 && pageSize == 0 {
	} else {
		limit = " ORDER BY start_time DESC LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
	}

	isSqlClass := "select count(*) from pg_class where relname = 'ai_cdr_" + start + "'"
	var count = 0
	var counts int64
	err := orm.NewOrm().Raw(isSqlClass).QueryRow(&count)
	var flowCount []AiCdr
	if count != 0 {
		sqlStr := "SELECT Id,Account_id,Callee,Caller,Start_time,End_time,Route_id,Fee_rate,Duration,Bill_balance,Record_base,Record_path,Task_id,Call_id,Intention,Hangup_dispostion,Term_cause,Term_status,Talk_crycle " +
			" FROM ai_cdr_" + start + intentionStr + limit
		countstr := "select count(*) from ai_cdr_" + start
		_, err = orm.NewOrm().Raw(sqlStr).QueryRows(&flowCount)
		err = orm.NewOrm().Raw(countstr).QueryRow(&counts)
		if err != nil {
			ErrorLog(err)
			return []AiCdr{}, 0, err
		}
	}
	return flowCount, counts, nil
}

//获取cdr 相关内容
func SearchCdrInfo(start string, userId int) (int, int, int, error) {
	var authStr = " "
	var authStr1 = " "
	if userId != 1 {
		authStr = " and account_id=" + strconv.Itoa(userId)
		authStr1 = " where account_id=" + strconv.Itoa(userId)
	}
	isSqlClass := "select count(*) from ai_cdr_" + start + authStr1
	userSql := "select count(*) from ai_cdr_" + start + " where intention=3 " + authStr
	jietongSql := "select count(*) from ai_cdr_" + start + " where duration>0 " + authStr
	var count = 0
	var user = 0
	var connect = 0
	err := orm.NewOrm().Raw(isSqlClass).QueryRow(&count)
	if err != nil {
		return 0, 0, 0, err
	}
	err = orm.NewOrm().Raw(userSql).QueryRow(&user)
	if err != nil {
		return 0, 0, 0, err
	}
	err = orm.NewOrm().Raw(jietongSql).QueryRow(&connect)
	if err != nil {
		return 0, 0, 0, err
	}
	return user, count, connect, nil
}

//获取cdr 相关内容
func SearchCdrInfos(taskId int64, start, end, caller, timemax, timemin, classify,uuid string, intention int, userId int) (int, int, int, error) {
	taskStr := " "
	callerStr := " "
	intentionStr := " "
	timemaxStr := " "
	timemimStr := " "
	classifyStr := " "
	useridStr := " "
	uuidStr := " "

	if caller != "" {
		callerStr = " AND caller='" + caller + "'"
	}

	if timemax != "" {
		timemaxStr = " AND duration>=" + timemax
	}

	if timemin != "" {
		timemimStr = " AND duration<=" + timemin
	}

	if taskId != 0 {
		taskStr = " AND task_id=" + strconv.FormatInt(taskId, 10)
	}

	if intention != 0 {
		intentionStr = " AND intention=" + strconv.Itoa(intention-1)
	}
	if uuid != "" {
		uuidStr = " AND call_id='" + uuid + "'"
	}


	if classify != "-1" {
		a,_:=strconv.Atoi(classify)
		if a >= 3 {
			classifyStr = " AND talk_crycle>=" + classify
		}else {
			classifyStr = " AND talk_crycle=" + classify
		}
	}

	if userId != 1 {
		useridStr = " AND account_id=" + strconv.Itoa(userId)
	}

	isSqlClass := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " + useridStr + "  AND" +
		" start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS')" + taskStr + callerStr + useridStr + classifyStr + uuidStr + intentionStr + timemaxStr + timemimStr
	userSql := "select count(*) from ai_cdr where intention=3 and start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS')  AND" +
		" start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS')" + taskStr + callerStr + useridStr + classifyStr + uuidStr + intentionStr + timemaxStr + timemimStr
	jietongSql := "select count(*) from ai_cdr where duration>0 and start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS')  AND" +
		" start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS')" + taskStr + callerStr + useridStr + classifyStr + uuidStr + intentionStr + timemaxStr + timemimStr
	var count = 0
	var user = 0
	var connect = 0
	err := orm.NewOrm().Raw(isSqlClass).QueryRow(&count)
	if err != nil {
		return 0, 0, 0, err
	}
	err = orm.NewOrm().Raw(userSql).QueryRow(&user)
	if err != nil {
		return 0, 0, 0, err
	}
	err = orm.NewOrm().Raw(jietongSql).QueryRow(&connect)
	if err != nil {
		return 0, 0, 0, err
	}
	return user, count, connect, nil
}


//获取cdr 相关内容
func Reportcdr(start, end string,userId int) ([]int, error) {
	useridStr := " "

	if userId != 1 {
		useridStr = " AND account_id=" + strconv.Itoa(userId)
	}

	unconnectStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and duration=0 " + useridStr
	connectStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and duration!=0 " + useridStr
	passStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and intention=0 and duration!=0 " + useridStr
	rejectStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and intention=1 and duration!=0 " + useridStr
	intentionStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and intention=3 and duration!=0 " + useridStr
	dangerStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and intention=2 and duration!=0 " + useridStr
	userStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and hangup_dispostion='recv_bye' " + useridStr
	fromStr := "select count(*) from ai_cdr where start_time>=to_timestamp('" + start + "', 'YYYY-MM-DD HH24:MI:SS') " +
	" and start_time<=to_timestamp('" + end + "', 'YYYY-MM-DD HH24:MI:SS') and hangup_dispostion='send_bye' " + useridStr
	var unconnect = 0//没接通
	var connect = 0//接通
	var user = 0//客户挂机
	var from = 0//平台挂机
	var pass = 0//普通肯定
	var reject = 0//普通拒绝
	var intention = 0//意向客户
	var danger = 0//强烈拒绝
	var arrs = []int{}
	err := orm.NewOrm().Raw(unconnectStr).QueryRow(&unconnect)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(connectStr).QueryRow(&connect)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(passStr).QueryRow(&pass)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(rejectStr).QueryRow(&reject)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(intentionStr).QueryRow(&intention)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(dangerStr).QueryRow(&danger)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(userStr).QueryRow(&user)
	if err != nil {
		return arrs, err
	}
	err = orm.NewOrm().Raw(fromStr).QueryRow(&from)
	if err != nil {
		return arrs, err
	}
	arrs=[]int{unconnect,connect,user,from,pass,reject,intention,danger}
	return arrs, nil
}

